# _*_ coding: utf-8 _*_
"""
@ 时间    ：2024/10/24 16:21
@ 作者    ：旺财
@ 文件    ：04-2 LightGBM-广告收益预测模型.py
@ 说明    ：   
"""
import pandas as pd
from lightgbm import LGBMRegressor
from sklearn.model_selection import train_test_split, GridSearchCV


df = pd.read_excel('广告收益数据.xlsx')
print(df.head())

x = df.drop(columns='收益')
y = df['收益']

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=123)

mode = LGBMRegressor(verbose=-1)
parameters = {
    'num_leaves': [15, 31, 62],
    'n_estimators': [20, 30, 50, 70],
    'learning_rate': [0.1, 0.2, 0.3, 0.4]
}
grid_search = GridSearchCV(mode, parameters, scoring='r2', cv=5)
grid_search.fit(x_train, y_train)
best_mode = grid_search.best_estimator_
print(f'最优参数: {grid_search.best_params_}')

a = pd.DataFrame()
a['预测值'] = list(best_mode.predict(x_test))
a['实际值'] = list(y_test)
print(a.head())

score = best_mode.score(x_test, y_test)
print(f'准确率为:{round(score*100, 2)}%')

b = pd.DataFrame()
b['特征名称'] = x.columns
b['特征重要性'] = best_mode.feature_importances_
print(b.sort_values(by='特征重要性', ascending=False))